package njust.csc.aeapi.utils

import njust.csc.aeapi.entity.AnalysisOrder
import org.springframework.util.DigestUtils
import org.springframework.web.multipart.MultipartFile
import java.nio.file.Path
import kotlin.io.path.*
import kotlin.math.roundToLong

/**
 * @Author ZhouHang
 * @Date 24/8/6 周二
 */

/**
 * 将 multipartFile 保存到指定位置
 * @receiver MultipartFile
 * @param savePath Path 文件保存地址
 * @return Path 保存的文件路径(包括名称)
 */
fun MultipartFile.saveTo(savePath: Path): Path {
    if (!savePath.exists()) savePath.createDirectories()
    val uploadedFile: Path = savePath.resolve(originalFilename ?: "unknown")
    transferTo(uploadedFile)
    return uploadedFile
}

/**
 * 对给定文件进行编码，得到一个唯一定位该文件的值
 * @receiver MultipartFile
 * @return String 分析号
 */
fun MultipartFile.getAnalysisNo(): String {
    return DigestUtils.md5DigestAsHex("$originalFilename $size".toByteArray())
}

/**
 * 对给定文件进行编码，得到一个唯一定位该文件的值
 * @receiver Path
 * @return String 分析号
 */
fun Path.getAnalysisNo(): String {
    return DigestUtils.md5DigestAsHex("$name ${fileSize()}".toByteArray())
}

/**
 * 求数组中所有数字的平均值
 * @receiver List<Long>
 * @return Long 平均值
 */
fun List<Long>.avg(): Double {
    return sum() / size.toDouble()
}

/**
 * 求数组中所有数字的中位数
 * @receiver MutableList<Long>
 * @return Double 中位数
 */
fun List<Long>.median(): Double {
    val sortedList = sorted()
    return if (size % 2 == 0) {
        (sortedList[size / 2 - 1] + sortedList[size / 2]).toDouble() / 2
    } else {
        sortedList[size / 2].toDouble()
    }
}

/**
 * 将毫秒转化为分钟
 * @receiver Double
 */
fun Double.toSecond(): Double {
    return ((this / 1000) * 100).roundToLong() / 100.0
}

fun AnalysisOrder.getPredicate(truth: String): String {
    if (truth == "gamble") {
        var predicate = "gamble"
        if (!isGamble)
            predicate = if (isSex) "sex" else if (isScam) "scam" else "white"
        return predicate
    }

    if (truth == "sex") {
        var predicate = "sex"
        if (!isSex)
            predicate = if (isGamble) "gamble" else if (isScam) "sex" else "white"
        return predicate
    }

    if (truth == "scam") {
        var predicate = "scam"
        if (!isScam)
            predicate = if (isGamble) "gamble" else if (isSex) "sex" else "white"
        return predicate
    }

    if (truth == "white") {
        return if (isGamble) "gamble"
        else if (isScam) "scam"
        else if (isSex) "sex"
        else "white"
    }

    return "error"
}

fun AnalysisOrder.getPredicate(): String {
    var ret = ""
    if (isScam) ret += " 涉诈"
    if (isSex) ret += " 涉黄"
    if (isGamble) ret += " 涉赌"
    if (ret.isEmpty()) ret += "普通"
    return ret
}

fun AnalysisOrder.getReason(): String {
    var ret = ""
    if (isScam) ret += " ${scamReason.replace("\n", " ")}"
    if (isSex) ret += " ${sexReason.replace("\n", " ")}"
    if (isGamble) ret += " ${gambleReason.replace("\n", " ")}"
    if (ret.isEmpty()) ret += judgeResult.replace("\n", " ")
    return ret
}
